Imports System.IO
Imports System.Net
Imports System.Text
Imports System.Web

''' <summary>
''' todo: change list to grid view
''' </summary>
''' <remarks></remarks>
Public Class RequestBuilderForm

    Private ReadOnly _AppPath As String = Application.StartupPath

    Private _Request As Request = Nothing
    Private _Timeout As Integer = Request.DEFAULT_TIMEOUT

    Private _DocElemName As String
    Private _PublicId As String
    Private _SystemId As String
    Private _Subset As String

    Private Sub btnAddKey_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddKey.Click

        Dim key As String = txtNewKey.Text
        lstKeys.Items.Add(key)

        btnClearKeys.Enabled = True
        ToggleMoveButtons()

        RequestDataChanged()

        With txtNewKey
            .Clear()
            .Focus()
        End With

    End Sub

    Private Sub btnRemoveKey_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRemoveKey.Click

        lstKeys.Items.Remove(lstKeys.SelectedItem)

        If lstKeys.Items.Count = 0 Then
            btnClearKeys.Enabled = False
        End If
        btnRemoveKey.Enabled = False

        ToggleMoveButtons()

        RequestDataChanged()

    End Sub

    Private Sub btnClearKeys_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClearKeys.Click

        lstKeys.Items.Clear()

        btnClearKeys.Enabled = False
        btnRemoveKey.Enabled = False

        RequestDataChanged()

    End Sub

    Private Sub btnCalc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalc.Click

        Dim address As String = txtAddress.Text

        If _Request IsNot Nothing Then
            Try
                Dim resp As Response = _Request.Send(address)
                ResponseCacheForm.Add(_Request, resp)
                MsgBox(resp.StatusCode)
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
        End If
    End Sub

    Private Sub btnCopy_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCopy.Click

        Dim txt As String = txtXml.Text

        Clipboard.Clear()
        Clipboard.SetText(txt)

    End Sub

    Private Sub RequestDataChanged()

        Dim requestXmlString As String

        RequestBuilder.Settings.OmitXmlDeclaration = chkOmitXmlDecl.Checked

        If optInformation.Checked Then
            Dim tool As String = txtServiceTool.Text
            Dim modality As String = txtModality.Text
            Dim model As String = txtModel.Text
            Dim language As String = txtLanguage.Text
            Dim sessionId As String = txtSessionId.Text
            Dim keyCount As Integer = lstKeys.Items.Count
            Dim keys(keyCount - 1) As String
            lstKeys.Items.CopyTo(keys, 0)
            grpGeneral.Enabled = True

            ValidateInformationRequest(tool, modality, model, language, sessionId)
            requestXmlString = RequestBuilder.BuildInformationRequest(tool, modality, model, language, sessionId, keys, _DocElemName, _PublicId, _SystemId, _Subset)
        ElseIf optFile.Checked Then
            Dim tool As String = txtServiceTool.Text
            Dim modality As String = txtModality.Text
            Dim model As String = txtModel.Text
            Dim identifier As String = txtIdentifier.Text
            Dim sessionId As String = txtSessionId.Text
            grpGeneral.Enabled = True

            ValidateFileRequest(tool, modality, model, identifier, sessionId)
            requestXmlString = RequestBuilder.BuildFileRequest(tool, modality, model, identifier, sessionId, _DocElemName, _PublicId, _SystemId, _Subset)
        ElseIf optSession.Checked Then
            Dim tool As String = txtServiceTool.Text
            Dim modality As String = txtModality.Text
            Dim model As String = txtModel.Text
            grpGeneral.Enabled = True

            ValidateSessionRequest(tool, modality, model)
            requestXmlString = RequestBuilder.BuildSessionRequest(tool, modality, model, _DocElemName, _PublicId, _SystemId, _Subset)
        Else
            grpGeneral.Enabled = False

            requestXmlString = ""

            RequestTypeError()
        End If

        txtXml.Text = requestXmlString

    End Sub

    Private Sub RequestTypeError()

        ErrorProvider1.Clear()
        ErrorProvider1.SetError(lblRequestType, "request type expected")

    End Sub

    Private Sub ValidateInformationRequest(ByVal tool As String, ByVal modality As String, ByVal model As String, ByVal language As String, ByVal sessionId As String)

        Dim msg As String
        ErrorProvider1.Clear()

        msg = RequestBuilder.ValidateServiceTool(tool)
        If msg IsNot Nothing Then
            ErrorProvider1.SetError(txtServiceTool, msg)
        End If

        msg = RequestBuilder.ValidateModality(modality)
        If msg IsNot Nothing Then
            ErrorProvider1.SetError(txtModality, msg)
        End If

        msg = RequestBuilder.ValidateModel(model)
        If msg IsNot Nothing Then
            ErrorProvider1.SetError(txtModel, msg)
        End If

        msg = RequestBuilder.ValidateLanguage(language)
        If msg IsNot Nothing Then
            ErrorProvider1.SetError(txtLanguage, msg)
        End If

        msg = RequestBuilder.ValidateSessionId(sessionId)
        If msg IsNot Nothing Then
            ErrorProvider1.SetError(txtSessionId, msg)
        End If
    End Sub

    Private Sub ValidateFileRequest(ByVal tool As String, ByVal modality As String, ByVal model As String, ByVal identifier As String, ByVal sessionId As String)

        Dim msg As String
        ErrorProvider1.Clear()

        msg = RequestBuilder.ValidateServiceTool(tool)
        If msg IsNot Nothing Then
            ErrorProvider1.SetError(txtServiceTool, msg)
        End If

        msg = RequestBuilder.ValidateModality(modality)
        If msg IsNot Nothing Then
            ErrorProvider1.SetError(txtModality, msg)
        End If

        msg = RequestBuilder.ValidateModel(model)
        If msg IsNot Nothing Then
            ErrorProvider1.SetError(txtModel, msg)
        End If

        msg = RequestBuilder.ValidateIdentifier(identifier)
        If msg IsNot Nothing Then
            ErrorProvider1.SetError(txtIdentifier, msg)
        End If

        msg = RequestBuilder.ValidateSessionId(sessionId)
        If msg IsNot Nothing Then
            ErrorProvider1.SetError(txtSessionId, msg)
        End If
    End Sub

    Private Sub ValidateSessionRequest(ByVal tool As String, ByVal modality As String, ByVal model As String)

        Dim msg As String
        ErrorProvider1.Clear()

        msg = RequestBuilder.ValidateServiceTool(tool)
        If msg IsNot Nothing Then
            ErrorProvider1.SetError(txtServiceTool, msg)
        End If

        msg = RequestBuilder.ValidateModality(modality)
        If msg IsNot Nothing Then
            ErrorProvider1.SetError(txtModality, msg)
        End If

        msg = RequestBuilder.ValidateModel(model)
        If msg IsNot Nothing Then
            ErrorProvider1.SetError(txtModel, msg)
        End If
    End Sub

    Private Sub txtAddress_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtAddress.TextChanged

        Dim txt As String = txtAddress.Text
        Dim isUri As Boolean
        Try
            Dim uri As New Uri(txt)
            isUri = uri.IsAbsoluteUri
        Catch ex As Exception
            isUri = False
        End Try

        grpRequestType.Enabled = isUri
        grpXml.Enabled = isUri
        btnCalc.Enabled = isUri

    End Sub

    Private Sub grpRequestType_EnabledChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles grpRequestType.EnabledChanged

        If grpRequestType.Enabled Then
            RequestDataChanged()
        Else
            grpGeneral.Enabled = False
        End If
    End Sub

    Private Sub optInformation_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles optInformation.CheckedChanged

        If optInformation.Checked Then
            grpGeneral.Enabled = True
            txtServiceTool.Enabled = True
            txtModality.Enabled = True
            txtModel.Enabled = True
            txtLanguage.Enabled = True
            txtSessionId.Enabled = True
            txtIdentifier.Enabled = False

            grpKeys.Enabled = True
        Else
            grpKeys.Enabled = False
        End If

        If optInformation.Focused Then
            RequestDataChanged()
        End If
    End Sub

    Private Sub optFile_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles optFile.CheckedChanged

        If optFile.Checked Then
            grpGeneral.Enabled = True
            txtServiceTool.Enabled = True
            txtModality.Enabled = True
            txtModel.Enabled = True
            txtLanguage.Enabled = False
            txtSessionId.Enabled = True
            txtIdentifier.Enabled = True
        End If

        If optFile.Focused Then
            RequestDataChanged()
        End If
    End Sub

    Private Sub optSession_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles optSession.CheckedChanged

        If optSession.Checked Then
            grpGeneral.Enabled = True
            txtServiceTool.Enabled = True
            txtModality.Enabled = True
            txtModel.Enabled = True
            txtLanguage.Enabled = False
            txtSessionId.Enabled = False
            txtIdentifier.Enabled = False
        End If

        If optSession.Focused Then
            RequestDataChanged()
        End If
    End Sub

    Private Sub GeneralChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSessionId.TextChanged, txtIdentifier.TextChanged, txtLanguage.TextChanged, txtModel.TextChanged, txtModality.TextChanged, txtServiceTool.TextChanged

        If TypeOf sender Is TextBox Then
            Dim txt As TextBox = sender
            If txt.Focused Then
                RequestDataChanged()
            End If
        End If

    End Sub

    Private Sub btnMoveDown_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMoveDown.Click

        Dim obj As Object = lstKeys.SelectedItem
        Dim index As Integer = lstKeys.SelectedIndex
        lstKeys.Items(index) = lstKeys.Items(index + 1)
        lstKeys.Items(index + 1) = obj

        RequestDataChanged()

    End Sub

    Private Sub btnMoveUp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMoveUp.Click

        Dim obj As Object = lstKeys.SelectedItem
        Dim index As Integer = lstKeys.SelectedIndex
        lstKeys.Items(index) = lstKeys.Items(index - 1)
        lstKeys.Items(index - 1) = obj

        RequestDataChanged()

    End Sub

    Private Sub lstKeys_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstKeys.SelectedIndexChanged

        ToggleMoveButtons()

        'If index <> -1 Then
        '    btnRemoveKey.Enabled = True
        'End If
        btnRemoveKey.Enabled = True
    End Sub

    Private Sub ToggleMoveButtons()

        btnMoveUp.Enabled = False
        btnMoveDown.Enabled = False

        Dim index As Integer = lstKeys.SelectedIndex
        If index > 0 Then
            btnMoveUp.Enabled = True
        End If
        If index >= 0 And index < lstKeys.Items.Count - 1 Then
            btnMoveDown.Enabled = True
        End If

    End Sub

    Private Sub XmlError(ByVal ex As Exception)

        ErrorProvider1.Clear()
        'ErrorProvider1.SetIconAlignment(txtXml, ErrorIconAlignment.BottomRight)
        ErrorProvider1.SetError(txtXml, ex.Message)
        ToolTip1.SetToolTip(txtXml, ex.Message)

    End Sub

    Private Sub txtXml_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtXml.TextChanged

        With tmrValidationDelay
            btnCalc.Enabled = False
            If .Enabled Then
                .Stop()
            End If
            .Start()
        End With
    End Sub

    Private Sub chkOmitXmlDecl_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkOmitXmlDecl.CheckedChanged

        If chkOmitXmlDecl.Focused Then
            RequestDataChanged()
        End If
    End Sub

    Private Sub btnBrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowse.Click

        Dim obj As Object = CreateObject("InternetExplorer.Application")
        obj.visible = True

    End Sub

    Private Sub RequestBuilderForm_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed

        With My.Settings
            .address = txtAddress.Text
            .omitXmlDecl = chkOmitXmlDecl.Checked
            '.docType = txtDocType.Text
            .docElemName = _DocElemName
            .publicId = _PublicId
            .systemId = _SystemId
            .subset = _Subset
        End With

    End Sub

    Private Sub RequestBuilderForm_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress

        If e.KeyChar = vbLf Then
            If ResponseCacheForm.Visible Then
                ResponseCacheForm.Visible = False
            Else
                ResponseCacheForm.Show(Me)
            End If
        End If
    End Sub

    Private Sub RequestBuilderForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        With My.Settings
            _DocElemName = IIf(.docElemName.Length > 0, .docElemName, Nothing)
            _PublicId = IIf(.publicId.Length > 0, .publicId, Nothing)
            _SystemId = IIf(.systemId.Length > 0, .systemId, Nothing)
            _Subset = IIf(.subset.Length > 0, .subset, Nothing)
            chkOmitXmlDecl.Focus()
            chkOmitXmlDecl.Checked = .omitXmlDecl
            txtAddress.Focus()
            txtAddress.Text = .address
            'txtDocType.Text = .docType
        End With

        'todo: why doesn't it work?
        Dim b As Boolean = txtServiceTool.Focus()

        'For Each c As Control In Controls
        '    If TypeOf c Is TextBox Then
        '        AddHandler c.KeyPress, AddressOf RequestBuilderForm_KeyPress
        '    End If
        'Next
    End Sub

    Private Sub chkShowResponse_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkShowResponse.CheckedChanged

        If chkShowResponse.Checked Then
            ResponseCacheForm.Show(Me)
        Else
            ResponseCacheForm.Hide()
        End If
    End Sub

    Private Sub tmrValidationDelay_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrValidationDelay.Tick

        Dim xml As String = txtXml.Text

        Dim r As Request
        Try
            r = Request.Parse(xml)
            If r Is Nothing Then
                RequestTypeError()
                'Else
                'AddHandler r.GetSavePath, AddressOf GetSavePath
            End If
        Catch ex As TypeInitializationException
            r = Nothing
            XmlError(ex.InnerException)
        Catch ex As Exception
            r = Nothing
            XmlError(ex)
        End Try

        If txtXml.Focused Then
            chkOmitXmlDecl.Checked = Not XmlString.HasDeclaration(xml)

            If TypeOf r Is InformationRequest Then
                Dim ir As InformationRequest = r
                optInformation.Checked = True
                txtServiceTool.Text = ir.Tool
                txtModality.Text = ir.Modality
                txtModel.Text = ir.Model
                txtLanguage.Text = ir.Language
                'txtIdentifier.Text = ""
                txtSessionId.Text = ir.SessionId

                lstKeys.Items.Clear()
                lstKeys.Items.AddRange(ir.Keys.ToArray())

                ValidateInformationRequest(ir.Tool, ir.Modality, ir.Model, ir.Language, ir.SessionId)
            ElseIf TypeOf r Is FileRequest Then
                Dim fr As FileRequest = r
                optFile.Checked = True
                txtServiceTool.Text = fr.Tool
                txtModality.Text = fr.Modality
                txtModel.Text = fr.Model
                'txtLanguage.Text = ""
                txtIdentifier.Text = fr.Identifier
                txtSessionId.Text = fr.SessionId

                ValidateFileRequest(fr.Tool, fr.Modality, fr.Model, fr.Identifier, fr.SessionId)
            ElseIf TypeOf r Is SessionRequest Then
                Dim sr As SessionRequest = r
                optSession.Checked = True
                txtServiceTool.Text = sr.Tool
                txtModality.Text = sr.Modality
                txtModel.Text = sr.Model
                'txtLanguage.Text = ""
                'txtIdentifier.Text = ""
                'txtSessionId.Text = ""

                ValidateSessionRequest(sr.Tool, sr.Modality, sr.Model)
            Else
                optInformation.Checked = False
                optFile.Checked = False
                optSession.Checked = False

                grpGeneral.Enabled = False

                'XmlError()
                'RequestTypeError()
            End If
        End If

        _Request = r
        _Request.Timeout = _Timeout

        btnCopy.Enabled = txtXml.Text.Length > 0

        tmrValidationDelay.Stop()
        btnCalc.Enabled = True

    End Sub

    Private Sub txtNewKey_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtNewKey.TextChanged

        btnAddKey.Enabled = txtNewKey.Text.Length > 0

    End Sub

    Private Sub btnDocType_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDocType.Click

        With DocTypeForm
            .DocElemName = _DocElemName
            .PublicId = _PublicId
            .SystemId = _SystemId
            .Subset = _Subset
            If .ShowDialog() = Windows.Forms.DialogResult.OK Then
                _DocElemName = .DocElemName
                _PublicId = .PublicId
                _SystemId = .SystemId
                _Subset = .Subset
                RequestDataChanged()
            End If
        End With
    End Sub

    Private Sub lnkAbout_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles lnkAbout.LinkClicked

        AboutForm.ShowDialog()

    End Sub

    Private Sub lnkOptions_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles lnkOptions.LinkClicked

        With OptionsForm
            .Timeout = _Timeout
            If .ShowDialog() = Windows.Forms.DialogResult.OK Then
                _Timeout = .Timeout
                If _Request IsNot Nothing Then
                    _Request.Timeout = _Timeout
                End If
            End If
        End With
    End Sub
End Class
